package com.example.a2023110445

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.appcompat.app.AppCompatActivity
import com.example.a2023110445.model.Player

class EditInfoActivity : AppCompatActivity() {
    
    private lateinit var etName: EditText
    private lateinit var etPhone: EditText
    private lateinit var rgGender: RadioGroup
    private lateinit var rbMale: RadioButton
    private lateinit var rbFemale: RadioButton
    private lateinit var btnSave: Button
    private lateinit var btnCancel: Button
    
    private lateinit var player: Player
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_info)
        
        player = intent.getParcelableExtra<Player>(MainActivity.EXTRA_PLAYER) ?: Player()
        
        initViews()
        loadPlayerInfo()
        
        btnSave.setOnClickListener {
            savePlayerInfo()
            val resultIntent = Intent()
            resultIntent.putExtra(MainActivity.EXTRA_PLAYER, player)
            setResult(RESULT_OK, resultIntent)
            finish()
        }
        
        btnCancel.setOnClickListener {
            finish()
        }
    }
    
    private fun initViews() {
        etName = findViewById(R.id.etName)
        etPhone = findViewById(R.id.etPhone)
        rgGender = findViewById(R.id.rgGender)
        rbMale = findViewById(R.id.rbMale)
        rbFemale = findViewById(R.id.rbFemale)
        btnSave = findViewById(R.id.btnSave)
        btnCancel = findViewById(R.id.btnCancel)
    }
    
    private fun loadPlayerInfo() {
        etName.setText(player.name)
        etPhone.setText(player.phone)
        when (player.gender) {
            getString(R.string.gender_male) -> rbMale.isChecked = true
            getString(R.string.gender_female) -> rbFemale.isChecked = true
        }
    }
    
    private fun savePlayerInfo() {
        player.name = etName.text.toString().trim()
        player.phone = etPhone.text.toString().trim()
        player.gender = when (rgGender.checkedRadioButtonId) {
            R.id.rbMale -> getString(R.string.gender_male)
            R.id.rbFemale -> getString(R.string.gender_female)
            else -> ""
        }
    }
}

